package io.chain.ko.security;

import java.io.IOException;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.LogoutHandler;

import com.alibaba.fastjson.JSON;

import io.chain.ko.ajax.AjaxResult;
import io.chain.ko.common.Const;
import io.chain.ko.entity.TUser;
import io.chain.ko.service.JWTTokenService;
import io.chain.ko.service.UserService;

public class JWTLogoutHandler implements LogoutHandler {
	
	private JWTTokenService jwtTokenService;
	private UserService userService;
	private Long tokenTimeout;
	
	public JWTLogoutHandler(JWTTokenService jwtTokenService, UserService userService,Long tokenTimeout) {		
		this.jwtTokenService = jwtTokenService;
		this.userService = userService;
		this.tokenTimeout=tokenTimeout;
	}

	@Override
	public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
		String authorization=request.getHeader(Const.AUTHORIZATION);
		String bearer=Const.BEARER;
		TUser tuser=null;
		boolean tokenValid=false;
		if(authorization!=null && authorization.startsWith(bearer)) {
			String token=authorization.substring(bearer.length());
			String username=jwtTokenService.parseToken(token);
			if(StringUtils.isNotEmpty(username)) {
				tuser=userService.findByUsername(username);
				if(tuser!=null && StringUtils.isNotEmpty(tuser.getToken())) {
					Long tokenTime=tuser.getTokenTime().getTime();
					Long currentTime=System.currentTimeMillis();
					if(tuser.getToken().equals(authorization) && currentTime<tokenTime+tokenTimeout) {
						SecurityContextHolder.getContext().setAuthentication(null);
						SecurityContextHolder.clearContext();
						tuser.setToken(null);
						tuser.setTokenTime(null);
						userService.updateUser(tuser);
						tokenValid=true;
					}
				}
			}
		}
		AjaxResult ajaxResult=new AjaxResult();
		ajaxResult.setStatus(200L);
		ajaxResult.setTimestamp(new Date());
		ajaxResult.setMessage(tokenValid?"退出成功":"无效的token");
		try {
			response.setContentType("application/json");
			response.getOutputStream().write(JSON.toJSONString(ajaxResult).getBytes());
			response.flushBuffer();
		} catch (IOException e) {
			
		}		
	}	

}
